<script setup lang="ts">
import { ref, defineProps, watch, onMounted, onBeforeUnmount } from 'vue'
import * as echart from 'echarts'
const props = defineProps({
  options: {
    type: Object,
    required: true,
    default: () => { },
  },
})
const chartDom = ref<HTMLElement | null>(null)
let chart: echart.ECharts | null = null
const handleResize = () => {
  chart && chart.resize()
}
onMounted(() => {
  //如果option有数据，则初始化图表
  initChart()
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
function initChart() {
  if (chart) {
    chart.clear()
    window.removeEventListener('resize', handleResize)
  }
  if (!props.options) {
    return
  }
  chart = echart.init(chartDom.value)
  chart.setOption(props.options)
  window.addEventListener('resize', handleResize)
}
watch(
  () => props.options,
  (newVal, oldVal) => {
    //说明option发生变化了
    initChart()
  }
)
</script>
<template>
  <div class="echartsEle" ref="chartDom"></div>
</template>
<style scoped>
.echartsEle {
  width: 100%;
  height: 100%;
}
</style>